package com.example.forum.services.impl;

import com.example.forum.dao.SystemConfigMapper;
import com.example.forum.model.SystemConfig;
import com.example.forum.services.ISystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统配置服务实现类
 */
@Service
@Slf4j
public class SystemConfigServiceImpl implements ISystemConfigService {

    @Autowired
    private SystemConfigMapper systemConfigMapper;

    // 配置组常量
    private static final String GROUP_BASIC = "basic";
    private static final String GROUP_CONTENT = "content";
    private static final String GROUP_EMAIL = "email";
    private static final String GROUP_INTEGRATION = "integration";

    @Override
    public String getConfigValue(String configKey) {
        if (StringUtils.isEmpty(configKey)) {
            return null;
        }
        
        SystemConfig config = systemConfigMapper.selectByConfigKey(configKey);
        return config != null ? config.getConfigValue() : null;
    }

    @Override
    public String getConfigValueOrDefault(String configKey, String defaultValue) {
        String value = getConfigValue(configKey);
        return value != null ? value : defaultValue;
    }

    @Override
    @Transactional
    public boolean saveOrUpdateConfig(String configKey, String configValue, String description, String groupName) {
        if (StringUtils.isEmpty(configKey)) {
            log.warn("配置键不能为空");
            return false;
        }
        
        try {
            SystemConfig existConfig = systemConfigMapper.selectByConfigKey(configKey);
            if (existConfig != null) {
                existConfig.setConfigValue(configValue);
                existConfig.setUpdateTime(new Date());
                if (!StringUtils.isEmpty(description)) {
                    existConfig.setDescription(description);
                }
                if (!StringUtils.isEmpty(groupName)) {
                    existConfig.setGroupName(groupName);
                }
                systemConfigMapper.updateByPrimaryKeySelective(existConfig);
            } else {
                SystemConfig newConfig = new SystemConfig();
                newConfig.setConfigKey(configKey);
                newConfig.setConfigValue(configValue);
                newConfig.setDescription(description);
                newConfig.setGroupName(groupName);
                Date now = new Date();
                newConfig.setCreateTime(now);
                newConfig.setUpdateTime(now);
                systemConfigMapper.insertSelective(newConfig);
            }
            
            return true;
        } catch (Exception e) {
            log.error("保存配置失败: " + e.getMessage(), e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean batchSaveOrUpdateConfig(Map<String, String> configs, String groupName) {
        if (configs == null || configs.isEmpty()) {
            log.warn("配置项为空");
            return false;
        }
        
        try {
            for (Map.Entry<String, String> entry : configs.entrySet()) {
                saveOrUpdateConfig(entry.getKey(), entry.getValue(), null, groupName);
            }
            return true;
        } catch (Exception e) {
            log.error("批量保存配置失败: " + e.getMessage(), e);
            return false;
        }
    }

    @Override
    public List<SystemConfig> getConfigsByGroup(String groupName) {
        if (StringUtils.isEmpty(groupName)) {
            return Collections.emptyList();
        }
        
        return systemConfigMapper.selectByGroupName(groupName);
    }

    @Override
    public List<SystemConfig> getAllConfigs() {
        return systemConfigMapper.selectAll();
    }

    @Override
    public Map<String, String> getConfigMapByGroup(String groupName) {
        List<SystemConfig> configs = getConfigsByGroup(groupName);
        
        return configs.stream()
                .collect(Collectors.toMap(
                        SystemConfig::getConfigKey, 
                        SystemConfig::getConfigValue, 
                        (v1, v2) -> v2
                ));
    }

    @Override
    public Map<String, String> getBasicSettings() {
        return getConfigMapByGroup(GROUP_BASIC);
    }

    @Override
    public Map<String, String> getContentSettings() {
        return getConfigMapByGroup(GROUP_CONTENT);
    }

    @Override
    public Map<String, String> getEmailSettings() {
        return getConfigMapByGroup(GROUP_EMAIL);
    }

    @Override
    public Map<String, String> getIntegrationSettings() {
        return getConfigMapByGroup(GROUP_INTEGRATION);
    }

    @Override
    @Transactional
    public boolean saveBasicSettings(Map<String, String> settings) {
        return batchSaveOrUpdateConfig(settings, GROUP_BASIC);
    }

    @Override
    @Transactional
    public boolean saveContentSettings(Map<String, String> settings) {
        return batchSaveOrUpdateConfig(settings, GROUP_CONTENT);
    }

    @Override
    @Transactional
    public boolean saveEmailSettings(Map<String, String> settings) {
        return batchSaveOrUpdateConfig(settings, GROUP_EMAIL);
    }

    @Override
    @Transactional
    public boolean saveIntegrationSettings(Map<String, String> settings) {
        return batchSaveOrUpdateConfig(settings, GROUP_INTEGRATION);
    }

    @Override
    @PostConstruct
    @Transactional
    public void initDefaultConfigs() {
        log.info("初始化系统默认配置...");

        // 检查是否已有配置
        List<SystemConfig> existingConfigs = getAllConfigs();
        if (!existingConfigs.isEmpty()) {
            log.info("系统已有{}项配置，跳过初始化", existingConfigs.size());
            return;
        }

        try {
            // 基本设置
            saveOrUpdateConfig("site.name", "IT技术论坛", "网站名称", GROUP_BASIC);
            saveOrUpdateConfig("site.description", "一个专注于IT技术分享和交流的论坛", "网站描述", GROUP_BASIC);
            saveOrUpdateConfig("site.logo", "/images/logo.png", "网站LOGO路径", GROUP_BASIC);
            saveOrUpdateConfig("site.favicon", "/favicon.ico", "网站图标路径", GROUP_BASIC);
            saveOrUpdateConfig("site.footer", "Copyright © 2023 IT技术论坛. All Rights Reserved.", "页脚信息", GROUP_BASIC);
            
            // 内容设置
            saveOrUpdateConfig("content.postLength.min", "10", "文章最小长度", GROUP_CONTENT);
            saveOrUpdateConfig("content.postLength.max", "50000", "文章最大长度", GROUP_CONTENT);
            saveOrUpdateConfig("content.commentLength.min", "2", "评论最小长度", GROUP_CONTENT);
            saveOrUpdateConfig("content.commentLength.max", "1000", "评论最大长度", GROUP_CONTENT);
            saveOrUpdateConfig("content.allowHtml", "false", "是否允许HTML内容", GROUP_CONTENT);
            saveOrUpdateConfig("content.allowAttachment", "true", "是否允许附件", GROUP_CONTENT);
            saveOrUpdateConfig("content.maxAttachmentSize", "10", "附件最大大小(MB)", GROUP_CONTENT);
            
            // 邮件设置
            saveOrUpdateConfig("mail.enable", "false", "是否启用邮件功能", GROUP_EMAIL);
            saveOrUpdateConfig("mail.host", "smtp.example.com", "SMTP服务器地址", GROUP_EMAIL);
            saveOrUpdateConfig("mail.port", "465", "SMTP服务器端口", GROUP_EMAIL);
            saveOrUpdateConfig("mail.username", "admin@example.com", "邮箱账号", GROUP_EMAIL);
            saveOrUpdateConfig("mail.password", "", "邮箱密码", GROUP_EMAIL);
            saveOrUpdateConfig("mail.from", "noreply@example.com", "发件人地址", GROUP_EMAIL);
            saveOrUpdateConfig("mail.fromName", "IT技术论坛", "发件人名称", GROUP_EMAIL);
            
            // 第三方集成设置
            saveOrUpdateConfig("integration.ga.enable", "false", "是否启用Google Analytics", GROUP_INTEGRATION);
            saveOrUpdateConfig("integration.ga.trackingId", "", "Google Analytics跟踪ID", GROUP_INTEGRATION);
            saveOrUpdateConfig("integration.github.enable", "false", "是否启用GitHub登录", GROUP_INTEGRATION);
            saveOrUpdateConfig("integration.github.clientId", "", "GitHub Client ID", GROUP_INTEGRATION);
            saveOrUpdateConfig("integration.github.clientSecret", "", "GitHub Client Secret", GROUP_INTEGRATION);
            
            log.info("系统默认配置初始化完成");
        } catch (Exception e) {
            log.error("初始化系统配置失败", e);
            throw e;
        }
    }
} 